<template>
  <div class="HomeMap-view">
    <!-- map -->
    <div ref="mapDemo" class="mapDemo"></div>
    <div v-show="drawMode === 'drawLine'" ref="mapButton" class="mapButton">
      <a-button type="primary" @click="onclickEventDrawLine">开始绘制</a-button>
      <a-button type="primary" style="margin-left: 10px;" @click="clearDrawing">清除路线</a-button>
    </div>
  </div>
</template>

<script>
import $ from 'jquery'
// import styleJson from './js/custom_map_config.json'
import Vue from 'vue'
import { gws84 } from './js/BD09-WGS84'
import qbuPoint from '@/assets/js/qbuPoint'
export default {
  name: 'Home-Map',
  components: {},

  props: {
    showLegendType: {
      type: Boolean,
      default: true,
    },
    BoundaryColor: {
      //地图区域边框颜色
      default: function () {
        return {}
      },
    },
    zoom: {
      //地图缩放
      type: Number,
      default: 17,
    },
    blueMap: {
      //是否深蓝色地图
      type: Boolean,
      default: true,
    },
    mapCenter: {
      //地图中心点
      default: function () {
        return {
          lng: '117.07149171065725',
          lat: '36.89521254833693',
          cricle: false,
          icon: {},
          legend: ''
        }
      },
    }
  },
  data() {
    return {
      mapActiveData: BMAP_NORMAL_MAP, //BMAP_SATELLITE_MAP
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: function (data, node) { },
      },
      map: null, //地图对象
      drawMode: 'drawPoint',
      iconSrc: 'assets/operationalSupervision/map/', //图片位置
      points: [],
      polyline: null,
      markers: [],
      isDrawing: false // 标记是否正在画线
      
    }
  },
  beforeDestroy() {
    if (this.map) {
      console.log('map=============', this.map)
      this.map.destroy()
      console.log('map=============', this.map)
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    //创建地图
    initMap() {
      this.map = new BMapGL.Map(this.$refs.mapDemo)
      Vue.prototype.mapCount = this.map //全局挂载使用mapv
      var centerPoint = new BMapGL.Point(this.mapCenter.lng, this.mapCenter.lat)
      this.map.centerAndZoom(centerPoint, this.zoom)
      this.map.enableScrollWheelZoom(true)
      // this.map.setMinZoom(5);
      // this.map.setMaxZoom(17);
      // this.map.getPanes().markerPane.style.zIndex = 500
      // this.map.setMapType(this.mapActiveData)
      // 地图区域边框颜色
      // var control = new BMapGL.Control();
      // control.setAnchor("BMAP_ANCHOR_TOP_LEFT");
      // map.addControl(control);
      var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
      this.map.addControl(zoomCtrl);
      var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
      this.map.addControl(scaleCtrl);
    },
    setCenterAndZoom(lnglat, zoom){
      var centerPoint = new BMapGL.Point(lnglat.lng, lnglat.lat)
      this.map.centerAndZoom(centerPoint, zoom);
    },
    setViewportToPolyline(polyline){
      this.map.setViewport(polyline.getPath());
    },
    removeOverlay(overlay){
      this.map.removeOverlay(overlay);
    },
    removeMarkers(markers) {
      markers.forEach(marker => {
        this.map.removeOverlay(marker); // 从地图中移除 Marker
      });
      markers.length = 0; // 清空数组
    },
    // 删除地图所有覆盖物
    clearOverlays() {
      try {
        this.map.clearOverlays()
      } catch {
        console.log('忽略一个类型错误')
        return true
      }
    },

    //   标题（广告牌）
    addMarker(lnglat, item, id) {
      let point = new BMapGL.Point(lnglat.lng, lnglat.lat);
      console.log('item', point, item, id)
      let content = `
                    <div class="addMarkerS" style="
                    height: 38px;
                    line-height: 38px;padding:0 30px">${item.name}</div>`
      var label = new BMapGL.Label(content, {
        position: point,
        offset: new BMapGL.Size(item.sx || 23, item.zy || -40), //label的偏移量，为了让label的中心显示在点上
      })
      label.setStyle({
        //给label设置样式，任意的CSS都是可以的
        color: item.color ? item.color : '#fff',
        fontSize: '20px', //字号
        border: '0', //边
        // height: '20px', //高度
        // fontWeight:'bold',
        // width: '100px', //宽
        textAlign: 'center', //文字水平居中显示
        lineHeight: '20px', //行高，文字垂直居中显示
        backgroundColor: 'transparent',
        //背景图片
        // background: 'url(' + require('@/' + this.iconSrc +  'waterName.png') + ') no-repeat center',
        background: 'url(' + require('@/' + this.iconSrc + item.bg + '.png') + ') no-repeat center bottom',
        cursor: 'pointer',
        backgroundSize: '100% 100%',
      })
      label.type = id
      this.map.addOverlay(label)
    },
    addImageMarker(lnglat, item, id){
      let iconPath = item.iconPath;
      let icon = require(`@/${iconPath}`);
      // 创建小车图标
      var myIcon = new BMapGL.Icon(icon, new BMapGL.Size(item.width || 32, item.height || 32));
      // 创建Marker标注，使用小车图标
      var pt = new BMapGL.Point(lnglat.lng, lnglat.lat);
      var marker = new BMapGL.Marker(pt, {
          icon: myIcon
      });
      // 将标注添加到地图
      this.map.addOverlay(marker); 
      return marker; 
    },
    onclickEventByAddMarker(imagePath, width, height, clickCallback){
      console.log('this map: ', this);
      const that = this;
      // 为地图添加点击事件监听
      that.map.addEventListener("click", function(e) {
        that.clearOverlays();
        // e.point 是点击位置的经纬度坐标
        console.log(`地图被点击了！坐标：${e.latlng.lng}, ${e.latlng.lat}`);

        that.$nextTick(() => {
          that.$emit('update-lnglat', e.latlng)
        });
        // 你可以在这里添加自定义操作，比如添加标记
        that.addImageMarker(e.latlng, {iconPath: imagePath, width: width || that.markerImageWidth, height: height || that.markerImageHeight});
        that.setCenterAndZoom(e.latlng, this.$refs.map.zoom);
        // const marker = new BMapGL.Marker(e.latlng);
        // that.map.addOverlay(marker);
        clickCallback && clickCallback(e);
      });
    },
    initDrawPointMode(){
      this.drawMode = 'drawPoint';
    },
    initDrawLineMode(){
      this.drawMode = 'drawLine';
    },
    onclickEventDrawLine(clickCallback){
      const that = this;
      that.isDrawing = true;
      // 单击事件：添加点
      that.map.addEventListener("click", that.handleMapClick);

      // 双击事件：结束画线
      that.map.addEventListener("rightclick", that.handleMapDbClick);
    },
    handleMapClick(e) {
      const that = this;
      let polyline = that.polyline;
      let points = that.points;
      if (!that.isDrawing) return;  
      var point = new BMapGL.Point(e.latlng.lng, e.latlng.lat);
      points.push(point);

      // 添加标记点
      // var marker = new BMapGL.Marker(point);
      // that.map.addOverlay(marker);
      let marker = this.addImageMarker(e.latlng, {iconPath: 'assets/icons/map/dot-red.png', width: 8, height: 8});
      that.markers.push(marker);
      
      // 实时更新临时折线
      if (points.length > 1) {
        if (polyline) that.map.removeOverlay(polyline); // 移除旧折线
        polyline = new BMapGL.Polyline(points, {
          strokeColor: "blue",
          strokeWeight: 2
        });
        that.map.addOverlay(polyline);
        that.polyline = polyline;
      }
    },
    handleMapDbClick() {
      const that = this;
      let points = that.points;

      if (points.length < 2) return;
      // 结束画线并移除事件监听
      that.stopDrawing();

      console.log("画线完成，坐标点：", points);
      let wkt = that.pointsToWKT(points); // 生成WKT坐标
      that.points = []; // 重置点数组
      that.$nextTick(() => {
        that.$emit('update-lineWkt', wkt)
      });
    },
    // 结束画线（移除事件监听）
    stopDrawing() {
      this.isDrawing = false;
      
      // 移除事件监听器
      this.map.removeEventListener("click", this.handleMapClick);
      this.map.removeEventListener("dblclick", this.handleMapDblClick);
    },
    
    // 清除画线
    clearDrawing() {
      const that = this;
      // 清除覆盖物
      if (that.polyline) {
        that.map.removeOverlay(that.polyline);
        that.polyline = null;
      }
      that.$nextTick(() => {
        that.$emit('update-lineWkt', null)
      });
      
      // 清除标记点
      that.markers.forEach(marker => this.map.removeOverlay(marker));
      that.markers = [];
      // 重置点数组
      that.points = [];
    },
    pointsToWKT(points) {
      if (!points || points.length === 0) return null;
      const coordinates = points.map(point => `${point.lng} ${point.lat}`).join(",");
      return coordinates;
    },
    pointsToWKT2(points) {
      if (!points || points.length === 0) return "LINESTRING EMPTY";
      
      const coordinates = points.map(point => `${point.lng} ${point.lat}`).join(",");
      
      if (points.length === 1) {
        return `POINT(${coordinates})`;
      } else {
        return `LINESTRING(${coordinates})`;
      }
    }
  },
}
</script>
<style scoped lang="less">
.HomeMap-view {
  height: 100%;
  margin: 0 auto;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.mapDemo {
  width: 100%;
  height: 100%;
}

.mapButton{
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 999;
}

</style>
<style scoped>
.BMapGL_cpyCtrl {
  display: none !important; /* 隐藏版权文本 */
}
.BMapGL_cpyCtrl span{
  display: none !important; /* 隐藏版权文本 */
}

.BMapGL_attribution {
  display: none !important; /* 隐藏地图数据来源 */
}
</style>